// =============订单详情页面=================
import {
  getOrder,
  deleteOrder,
  alterOrderStatus
} from '../../../../api/orderApi'
import {
  payNow,
  showCancelActionSheet,
  cancelOrder
} from '../../../../util/tools'
import {
  goodsSelectAmountPlus
} from '../../../../api/cartApi'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    order: {
      orderid: "", //订单编号
      status: '', //订单状态
      //订单收货地址信息
      name: "", //收货人名字
      phone: '', //收货人手机号
      address: '', //详细地址(包括地址名称和门牌号)
      goodslist: [],
      createtime: "", //订单的创建时间
      createtimeStr: "",
      endtime: "", //订单的完成时间
      totalmoney: "", //订单的总金额
      sale: "", //优惠
      resultmoney: '', //订单实付款
    },
    time: 0, //订单的付款时间范围(当前时间减去订单的创建时间)
    timeData: {}, //时间对象
    unfoldGoodsList: [], //展开的商品列表数据
    packupGoodsList: [], //收起时展示的商品列表数据
    open: false, //是否展开
    showText: '显示更多',
    showCancelOrderBtn: false, //是否显示取消订单按钮
    showDelOrderBtn: false, //是否展示删除订单按钮
    showPayNow: false, //是否显示立即付款按钮
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("订单详情页面加载...====================================================", options);
    let id = options.id
    console.log("要请求的订单id:", id);
    //从服务端搜索相应的订单信息
    getOrder(id).then((res) => {
      console.log("请求订单详细信息结果:", res);
      if (res.code === 2000) {
        this.setData({
          order: res.data.orderDetails
        })
        //设置显示的订单列表和隐藏的订单列表
        let list = this.data.order.ordergoods
        this.setData({
          unfoldGoodsList: list.slice(0, 3),
          packupGoodsList: list.slice(3)
        })
        //如果是未支付订单,设置倒计时时间
        if (this.data.order.status === 'waitPay') {
          console.log("待支付订单,计算倒计时");
          let countDown = 30 * 60 * 1000 - (Date.now() - this.data.order.createtime)
          this.setData({
            time: countDown
          })
        }
        //设置要显示的按钮
        this.setBtn()
      } else {
        console.log("查询订单详细信息时服务器出现异常");
      }
    }).catch((err) => {
      console.log("请求订单详细信息失败", err);
      wx.showToast({
        title: '网络开小差了,请稍后重试',
        icon: 'none'
      })
    })
  },
  /**
   * 定时器的回调函数
   * @param {e} e
   */
  changeTime(e) {
    // console.log("定时器的时间改变了:", e.detail);
    this.setData({
      timeData: e.detail
    })
  },
  //复制订单编号
  copyOrderId() {
    console.log("复制订单编号");
    wx.setClipboardData({
      data: this.data.order.orderid,
    })
  },
  /**
   * 查看商品详情页面
   * @param {e} e 
   */
  lookGoods(e) {
    console.log("从订单详情页面进入商品详情页面================");
    wx.navigateTo({
      url: '../../../main/goodDetails/index?goodsId=' + e.currentTarget.dataset.id,
    })
  },
  /**
   * 改变打开和收起的状态
   */
  changeOpen() {
    console.log("点击了显示和收起的状态按钮");
    this.setData({
      open: !this.data.open
    })
    let str = this.data.open ? '收起' : '显示更多'
    this.setData({
      showText: str
    })
  },
  /**
   * 设置要显示的按钮
   */
  setBtn() {
    console.log("设置订单详细信息页面显示的按钮---------------------------------------");
    let status = this.data.order.status
    //是否显示删除和取消订单的临时变量
    let showDel, showCancel, showPayNow;
    if (status === 'waitPay') {
      //待支付
      showDel = false
      showCancel = true
      showPayNow = true
    } else if (status === 'waitReceive') {
      //待收货
      showDel = false
      showCancel = false
      showPayNow = false
    } else if (status === 'timeoutCancel') {
      //超时自动取消
      showDel = true
      showCancel = false
      showPayNow = false
    } else if (status === 'handCancel') {
      //手动取消
      showDel = true
      showCancel = false
      showPayNow = false
    } else if (status === 'completed') {
      //订单已完成
      showDel = true
      showCancel = false
      showPayNow = false
    }
    this.setData({
      showDelOrderBtn: showDel,
      showCancelOrderBtn: showCancel,
      showPayNow: showPayNow
    })
  },
  /**
   * 取消订单
   */
  cancelOrder() {
    console.log("取消订单===========================");
    showCancelActionSheet().then((res) => {
      // console.log("取消订单成功:", res);
      //根据选择的取消订单原因,进行相应的处理
      this.handleCancel(res)
    }).catch((err) => {
      console.log("取消订单失败:", err);
      // wx.showToast({
      //   title: '网络异常,请稍后重试',
      //   icon: "none"
      // })
    })
  },
  /**
   * 删除订单
   */
  delOrder() {
    console.log("删除订单============================");
    let refThis = this
    wx.showModal({
      title: '删除订单',
      content: "订单一旦删除将不可恢复,确认删除吗?",
      success(res) {
        console.log("是否删除订单:", res);
        if (res.confirm) {
          deleteOrder(refThis.data.order.orderid).then((res) => {
            if (res.code === 2000) {
              console.log("订单已删除", res);
              wx.showToast({
                title: '订单已删除',
                duration: 800
              })
              //定时跳转到上一页
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                })
              }, 801)
            } else {
              console.log("订单删除失败");
            }
          }).catch((err) => {
            console.log("订单删除失败", err);
          })
        } else {
          console.log("已取消删除订单----------------------");
        }
      }
    })
  },
  /**
   * 立即付款
   */
  payNow() {
    let money = this.data.order.resultmoney
    let id = this.data.order.orderid
    payNow(money, id).then(() => {
      console.log("点击确认支付后.......");
      getApp().orderPayment("商水超市-精品蔬菜", parseInt(money*100)).then((res) => {
        console.log("支付完成的操作");
        //如果支付成功,修改订单的状态
        if (res.errMsg == "requestPayment:ok") {
          //修改订单的状态
          //此时订单状态为已支付->待收货
          alterOrderStatus(id, "waitReceive").then((res) => {
            console.log("修改订单状态成功:", res);
            if (res.code === 2000) {
              wx.showToast({
                title: '支付成功'
              })
              //支付成功后跳转到订单列表页面
              wx.navigateBack({
                delta: 1,
              })
              // setTimeout(()=>{
              // },500)
            } else {
              console.log("修改订单状态失败");
              wx.showToast({
                title: '服务器开小差了,请稍后重试',
                icon: 'error'
              })
            }
          }).catch((err) => {
            console.log("修改订单状态出现异常:", err);
          })
        } else {
          //requestPayment:fail cancel
          console.log("取消支付");
          wx.showToast({
            title: '您取消了支付',
            icon: 'error'
          })
        }
        //如果支付失败,不改变
      })

    }).catch(() => {
      console.log("点击了取消支付");
      wx.showToast({
        title: '您取消了支付',
        icon: 'error'
      })
    })
  },
  /**
   * 处理选择取消订单
   */
  handleCancel(res) {
    let id = this.data.order.orderid
    console.log("订单列表页面,要取消的订单的id", id);
    let goodsList;
    getOrder(id).then((re) => {
      console.log("取消订单时获取的订单详细信息:", re);
      goodsList = re.data.orderDetails.ordergoods
      console.log("goodsList=>", goodsList);
      switch (res) {
        case "cancelOrder":
          //取消订单
          this.handlecancelOrder(id)
          break;
        case "addressErr":
          //然后回到提交订单页面,需要先请求订单中的商品列表
          this.handleAddressErr(id, goodsList)
          break;
        case "goodsErr":
          //商品选错了,将商品放入购物车,然后删除订单,跳转到购物车页面
          this.handleGoodsErr(id,goodsList)
          break;
        default:
          console.log("没有选择取消订单原因");
          break;
      }
    }).catch((err) => {
      console.log("取消订单时获取订单的详细信息失败:", err);
    })

  },
  /**
   * 处理直接取消订单,取消订单原因为不想买了或者其他
   */
  handlecancelOrder(id) {
    cancelOrder(id).then((res) => {
      console.log("取消订单成功");
      wx.showToast({
        title: '订单已取消',
        duration: 800
      })
      //放回订单列表页面
      setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        })
      }, 801)
    })
  },
  /**
   * 处理收货地址选错了
   * @param {id} id 
   * @param {goodsList} goodsList 
   */
  handleAddressErr(id, goodsList) {
    deleteOrder(id).then((r) => {
      console.log("订单删除成功");
      //跳转到提交订单页面
      wx.navigateTo({
        url: '/pages/submit-order/submit-order',
        success(r) {
          r.eventChannel.emit("acceptDataFromCartPage", {
            goodsList
          })
        }
      })
    }).catch((err) => {
      console.log(err);
    })
  },
  /**
   * 处理商品选错了的取消订单情况
   */
  handleGoodsErr(id, goodsList) {
    let addCount;
    goodsList.forEach(element => {
      console.log("要添加的商品:", element);
      // goodsSelectAmountPlus
      let good = {
        goods_id: element.id,
        specificationid: element.specid,
        amount: element.count
      }
      goodsSelectAmountPlus(good).then(rs => {
        console.log("添加到购物车成功");
        addCount++;
      }).catch(err => {
        console.log("添加到购物车失败");
      })
    });
    console.log("购物车徽标已初始化-----------------------------");
    deleteOrder(id).then((r) => {
      console.log("取消订单时删除订单成功", r);
      wx.switchTab({
        url: '/pages/cart/index',
      })
    }).catch((err) => {
      console.log("取消订单时删除订单失败:", err);
    })
  },
})